package org.finesys.common.log.trace.interceptor.httpclient5;

import lombok.extern.slf4j.Slf4j;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpRequestInterceptor;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.finesys.common.log.trace.interceptor.AbstractInterceptor;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.springframework.util.StringUtils;

import java.io.IOException;

import static org.finesys.common.log.constants.TraceConstants.*;

@Slf4j
public class TraceIdHttpRequest5Interceptor extends AbstractInterceptor implements HttpRequestInterceptor {


    @Override
    public void process(HttpRequest request, EntityDetails entityDetails, HttpContext httpContext) throws HttpException, IOException {
        try {
            if (StringUtils.hasText(getTraceId())) {
                request.addHeader(TRACE_ID, getTraceId());
                request.addHeader(SPAN_ID, getSpanId());
                request.addHeader(PARENT_ID, getParentId());
                super.executeBefore(HTTP_CLIENT_EXEC_BEFORE);
            } else {
                if (log.isInfoEnabled()) {
                    log.info(LogstashUtil.marker(), "current thread have not the traceId!");
                }
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(LogstashUtil.exceptionMarker(), "HttpClient http header set traceId exception!", e);
            }
        }
    }


}
